//
//  SLAccessManagerView.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/26.
//

#import "SLAccessManagerView.h"
#import "SLAccessListCell.h"
static  NSString *const kCellId = @"SLAccessListCell";


@interface SLAccessManagerView ()<UITableViewDelegate,UITableViewDataSource>{
    
    SLLockModel *_lockModel;
}
@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)UITableView *tableView;

@end

@implementation SLAccessManagerView
-(void)awakeFromNib{
    [super awakeFromNib];
    _topView.layer.cornerRadius = 20;
    _topView.layer.masksToBounds = YES;
    
    _midView.layer.cornerRadius = 20;
    _midView.layer.masksToBounds = YES;
    
    _tableBgView.layer.cornerRadius = 20;
    _tableBgView.layer.masksToBounds = YES;
    [self setBtnSelectStyle:_leftBtn];
    [self setBtnSelectStyle:_rightBtn];
    _rightBtn.selected = NO;
    _leftBtn.selected = YES;
    _curBtn = _leftBtn;
    [self updateBtnUI];
    [_tableBgView addSubview:self.tableView];
    
    
    
}

-(void)setBtnSelectStyle:(UIButton *)btn{
    // 创建渐变图层
    UIGraphicsBeginImageContextWithOptions(btn.bounds.size, NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawLinearGradient(context,
                                CGGradientCreateWithColors(NULL,
                                                           (__bridge CFArrayRef)@[(id)KColor_O.CGColor, (id)KColor_Y.CGColor],
                                                           (CGFloat[]){0, 1}),
                                CGPointMake(0, 0),
                                CGPointMake(btn.bounds.size.width, 0),
                                kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [btn setTitleColor:KWhiteColor_text forState:UIControlStateNormal];
    [btn setTitleColor:KColor_1 forState:UIControlStateSelected];
    [btn setBackgroundImage:gradientImage forState:UIControlStateSelected];
}

-(void)updateBtnUI{
    _leftBtn.layer.cornerRadius = 0;
    _rightBtn.layer.cornerRadius = 0;
    _curBtn.layer.cornerRadius = 20;
    _curBtn.layer.masksToBounds = YES;
}

- (IBAction)btnAction:(id)sender {
    if (sender == _refreshBtn) {
        if (self.btnBlock) self.btnBlock(1);
    }
}

-(void)startRefreshAnimation{
    [_refreshBtn.imageView rotate360Degree:0.4];
}

-(void)stopRefreshAnimation{
    [_refreshBtn.imageView.layer removeAllAnimations];
}

- (IBAction)switchAction:(UIButton *)sender {
    if (_curBtn == sender) {
        return;
    }
    
    _curBtn.selected = NO;
    sender.selected = YES;
    _curBtn = sender;
    [self updateBtnUI];
    NSInteger lockType = _curBtn == _rightBtn ? 2:1;
    [self refreshWith:_lockModel lockType:lockType];
    
}

-(void)refreshSubViewWith:(SLLockModel *)model{
    NSInteger lockType = _curBtn == _rightBtn ? 2:1;
    [self refreshWith:model lockType:lockType];
}

-(void)refreshWith:(SLLockModel *)model lockType:(NSInteger)lockType{
    
    _lockModel = model;
    [self.dataArray removeAllObjects];
    __block CGFloat height = 0;
    [model.keys enumerateObjectsUsingBlock:^(SLLockKeyModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.lockType == lockType) {
            [_dataArray addObject:obj];
            height += [SLAccessListCell cellHeight:obj];
        }
    }];
    
    _tableBgHeight.constant = height;
    _tableView.frame = CGRectMake(0, 0, kScreenWidth-40, height);
    [_tableView reloadData];
    if (height == 0) {
        _tabBgTopSpace.constant = 15;
        _topTipLbl.text = lockType == 1 ? kLocalString(@"Tap the “+” button below to add your first fingerprint.") : kLocalString(@"Tap the “+” button below to create bluetooth key.");
    }else{
        _tabBgTopSpace.constant = 0;
        _topTipLbl.text = @"";
    }
    if (self.heightChangeBlock) {
        self.heightChangeBlock(height);
    }
}

#pragma mark - ================<tableViewDataSource>===============
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SLAccessListCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    SLLockKeyModel *model = _dataArray[indexPath.row];
    cell.line.hidden = indexPath.row == _dataArray.count-1;
    cell.model = model;
    return cell;
}

#pragma mark - ================<UITableViewDelegate>===============
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SLLockKeyModel *model = _dataArray[indexPath.row];
    return [SLAccessListCell cellHeight:model];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UITableViewHeaderFooterView *headview = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    if (!headview) {
        headview = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"head"];
        headview.frame = CGRectMake(0, 0, kScreenWidth, 0.1);
        headview.contentView.backgroundColor = KClearColor;
    }
    return headview;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"foot"];
    if (!footerView) {
        footerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"foot"];
        footerView.frame = CGRectMake(0, 0, kScreenWidth, 0.1);
        footerView.contentView.backgroundColor = KClearColor;
    }
    return footerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SLLockKeyModel *model = _dataArray[indexPath.row];
    if (self.cellCilckBlock) {
        self.cellCilckBlock(model);
    }
}


#pragma mark - ================<懒加载>===============
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 50;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:kCellId bundle:nil] forCellReuseIdentifier:kCellId];
        _tableView.backgroundColor = KClearColor;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.scrollEnabled = NO;
    }
    return _tableView;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}


@end
